<template>
  <div>
    <MainContent title="聚合页装修">
      <template #tab-bar>
        <el-radio-group v-model="tabPosition">
          <el-radio-button plain label="page">界面</el-radio-button>
          <el-radio-button plain label="list">列表</el-radio-button>
        </el-radio-group>
      </template>
      <MainContentSearchBarWrapper>
        <SearchBar inline>
          <template #normal>
            <el-form-item>
              <el-input v-model="params.name" placeholder="页面名称" clearable>
              </el-input>
            </el-form-item>
          </template>
          <template #toolbar>
            <el-form-item>
              <el-button type="primary" @click="getPageList">查询</el-button>
              <el-button type="primary" icon="Plus" v-has="['230101']"
                @click="$router.push(`/activity/pageList/createEditApp/0`)">新增</el-button>
              <!-- TODO 加权限 -->
              <el-button type="primary" @click="showExportData = true">导出</el-button>
            </el-form-item>
          </template>
        </SearchBar>
      </MainContentSearchBarWrapper>
      <div v-if="tabPosition == 'list'">
        <el-table :data="state.tableData" stripe v-loading="state.isLoading">
          <el-table-column prop="name" label="页面名称" min-width="180" />
          <!-- <el-table-column prop="id" label="页面ID" min-width="100" /> -->
          <el-table-column prop="updateTime" label="更新时间" min-width="100">
            <template #default="scope">
              {{ new Date(scope.row.updateTime).format("yyyy-MM-dd hh:mm") }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="status" label="状态" min-width="100">
            <template #default="scope">
              {{ scope.row.status ? "已发布" : "未发布" }}
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="visitorNum" label="累计访客数/累计浏览量" min-width="120">
            <template #default="scope">
              {{
                  scope.row.visitorNum
                    ? scope.row.visitorNum
                    : "" + "/" + scope.row.pageViewNum
                      ? scope.row.pageViewNum
                      : ""
              }}
            </template>
          </el-table-column> -->
          <el-table-column label="页面链接" prop="pageLink" min-width="200">
            <template #default="scope">
              {{ `${previewPath}/${scope.row.id}` }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button type="text" size="small" v-has="['230102']"
                @click="$router.push(`/activity/pageList/createEditApp/${scope.row.id}`)">装修
              </el-button>
              <el-button type="text" size="small" v-has="['230103']" @click="promote(scope.row.id)">预览</el-button>
              <el-dropdown @command="handleCommand($event, scope.row)" placement="top">
                <div style="margin-left: 10px; cursor: pointer">
                  <!-- <el-icon :size="20"><More /></el-icon> -->
                  <el-button type="primary" link size="small" v-has="['230104', '230105']">更多</el-button>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="copy" v-has="['230104']">复制</el-dropdown-item>
                    <el-dropdown-item command="delPage" v-has="['230105']">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-list" v-else>
        <!-- <el-row> -->
        <div class="card-list">
          <div class="card-wrap" :key="item.id" v-for="item in state.tableData">
            <!-- <el-col :span="4" > -->
            <div class="actapp-card">
              <div class="img-wrapper">
                <img :src="item.img" alt="">
              </div>
              <div class="card-content">
                <el-tooltip  placement="top" :content="item.name" effect="light">
                  <div class="card-name">{{ item.name }}</div>
                </el-tooltip>
                <div class="card-desc"> {{ new Date(item.updateTime).format("yyyy-MM-dd hh:mm") }} 更新</div>
                <div class="card-desc">{{ item.createUserName
                }} 创建</div>
              </div>
              <div class="card-overloay">
<div class="preview-top">
  <div class="preview-btn" @click="promote(item.id)">预览</div>
</div>
                <div class="preview-bottom">
                  <div @click="$router.push(`/activity/pageList/createEditApp/${item.id}`)" class="btn" v-has="['230102']"><img class="icon" src="@/assets/pointsMall/mallPage/decorate.png" alt="装修">
                    <div class="label">
                      装修
                    </div>
                  </div>
                  <div @click="copy(item)" class="btn" v-has="['230104']">
                    <img class="icon" src="@/assets/pointsMall/mallPage/copy.png" alt="复制">
                    <div class="label">
                      复制
                    </div>
                  </div>
                  <div @click="delPage(item)" class="btn" v-has="['230105']"> <img class="icon" src="@/assets/pointsMall/mallPage/delete.png" alt="删除">
                    <div class="label">
                      删除
                    </div>
                  </div>
                </div>
              </div>
              <!-- <div class="actapp-item">
                <div class="actapp-img">
                  <div class="actapp-img_container">
                    <img :src="item.img" alt="" />
                  </div>
                </div>
                <div class="actapp-name">{{ item.name }}</div>
              </div>
              <div class="actapp-qrcode">
                <div class="actapp-container">
                  <div class="qrcode-container">
                    <qrcode-vue :value="`${previewPath}/${item.id}`" :size="80" level="H" />
                  </div>
                  <p>预览</p>
                  <div class="tool-btn">
                    <div @click="$router.push(`/activity/pageList/createEditApp/${item.id}`)" v-has="['230102']">
                      <el-icon>
                        <Edit />
                      </el-icon>
                      <p>装修</p>
                    </div>
                    <div @click="copy(item)" v-has="['230104']">
                      <el-icon>
                        <CopyDocument />
                      </el-icon>
                      <p>复制</p>
                    </div>
                    <div @click="delPage(item)" v-has="['230105']">
                      <el-icon>
                        <Delete />
                      </el-icon>
                      <p>删除</p>
                    </div>
                  </div>
                </div>
              </div> -->
            </div>
          </div>
        </div>
        <!-- </el-col> -->
        <!-- </el-row> -->
      </div>

      <div class="page">
        <el-pagination v-model:currentPage="params.currentPage" v-model:page-size="params.showCount"
          :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <el-dialog class="dialog-form" v-model="dialogFormVisible" title="复制页面" width="30%" :before-close="resetForm"
        :close-on-click-modal="false">
        <el-form :model="form" ref="manageForm" :rules="rules" label-width="80px">
          <el-form-item label="页面名称" prop="name">
            <el-input v-model="form.name" autocomplete="off" placeholder="页面名称" maxlength="30" show-word-limit />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetForm()">取消</el-button>
            <el-button type="primary" @click="submitForm(manageForm)">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- <el-dialog class="dialog-form" v-model="promoteVisible" title="微信扫码预览" width="30%" :close-on-click-modal="false">
        <qrcode-vue style="margin: 10px auto; display: block" :value="`${previewPath}/${promoteId}`" :size="100"
          level="H" />
        <p style="margin: 10px auto; display: block; text-align: center">
          微信扫码预览
        </p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="promoteVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog> -->
      <Dialog :model-value="promoteVisible" title="扫码预览" :width="500" @close="promoteVisible = false">
        <div class="qrcode-container">
          <qrcode-vue :value="pageLink" :size="200" level="H" />
          <div class="tips">
            <div>手机扫左边二维码预览</div>
            <div>
              你也可以打开
              <a :href="pageLink" target="_blank">新窗口预览</a>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <!-- <el-button
          v-clipboard="`${link}`"
          v-clipboard:success="clipboardSuccess"
          >复制链接</el-button
        > -->
            <el-button @click="copyItemUrl">复制链接</el-button>
            <el-button type="primary" @click="promoteVisible = false">关闭</el-button>
          </span>
        </template>
      </Dialog>
      <exportData v-model:show-dialog="showExportData" :search-data="params" title="落地页" export-type="merchantPageExport">
      </exportData>
    </MainContent>
  </div>
</template>
<script lang="ts">
export default {
  name: 'AppPage'
}
</script>
<script lang="ts" setup>
// 活动 => 落地页管理

import { reactive, onMounted } from "vue";

import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  pageList,
  editPage,
  getPageInfo,
  del,
} from "@/api/actapp";
import QrcodeVue from "qrcode.vue";
import { debounceUtils } from "@/utils/index.js";
import exportData from "@/components/exportData/exportData.vue";
import { getPreviewUrl } from "@/api/pointsMall";
console.log(useStore())
// filterTemplate,
const router = useRouter();
const route = useRoute();
const showExportData = ref(false)
const state = reactive({
  total: 0,
  isLoading: false,
  tableData: [] as Array<any>,
});
const params = ref({
  name: "",
  type: 2,
  showCount: 10,
  currentPage: 1,
});
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  params.value.showCount = val;
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  params.value.currentPage = val;
};
const tabPosition = ref("page");
let form = ref({
  name: "",
});
const dialogFormVisible = ref(false);
const promoteVisible = ref(false);
const promoteId = ref(0);
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入页面名称",
      trigger: "blur",
    },
  ],
});
const manageForm = ref<FormInstance>();
let copyItem = {
  name: "",
};
const resetForm = () => {
  form.value = {
    name: "",
  };
  manageForm.value?.resetFields();
  dialogFormVisible.value = false;
};
const copyItemUrl = () => {
  let oInput = document.createElement("input");
  // 将想要复制的值
  oInput.value = pageLink.value;
  // 页面底部追加输入框
  document.body.appendChild(oInput);
  // 选中输入框
  oInput.select();
  // 执行浏览器复制命令
  document.execCommand("Copy");
  // 复制后移除输入框
  ElMessage({
    showClose: true,
    message: "复制成功",
    type: "success",
  });
  oInput.remove();
};
const submitForm = (formEl: FormInstance | undefined, edit: any) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      copyItem.name = form.value.name;
      const rs = await editPage(copyItem);
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "复制成功",
        });
        resetForm();
        getPageList();
      }
    } else {
      console.log("报错啦！请重新使一下", fields);
    }
  });
};
const store = useStore();
const previewPath = `${(window as any).VUE_APP_URL[import.meta.env.MODE].appPreviewPath}${store.state.user.merchant.merchantCode}#/activity/page`;

const getPageList = debounceUtils(async (): Promise<void> => {
  state.isLoading = true;
  const rs: any = await pageList(params.value);
  if (rs.code == 200) {
    state.total = rs.page.totalResult;
    state.tableData = rs.payload;
  }
  state.isLoading = false;
}, 500);
const copy = async (data: any) => {
  const rs = await getPageInfo({ id: data.id });
  delete rs.payload.id;
  copyItem = { ...rs.payload };
  dialogFormVisible.value = true;
};
const pageLink = ref("")
const promote = async (id: number) => {
  let previewData: any = await getPreviewUrl({ id: id })
  if (previewData.code === 200) {
    pageLink.value = previewData.payload.previewUrl;
    promoteVisible.value = true;
  }
};
const delPage = (row: any) => {
  ElMessageBox.confirm("是否确定删除该活动页面", "确认提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs: any = await del({ ids: [row.id], names: [row.name] });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getPageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
const handleCommand = (command: string, row: any) => {
  if (command === "delPage") {
    delPage(row);
  } else if (command === "copy") {
    copy(row);
  }
};
watch(params.value, (val) => {
  getPageList();
});
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getPageList();
  },
  {
    deep: true
  }
)
onMounted(() => {
  getPageList();
});
</script>
<style lang="scss" scoped>
:deep(.el-table) {
  margin: 0 auto;
}

.page-list {
  min-height: 200px;
}

.card-list {
  min-width: 520px;
  overflow-x: auto;
  display: flex;
  flex-wrap: wrap;

  .card-wrap {
    height: 340px;
    margin-bottom: 20px;
    padding-right: 20px;
    box-sizing: border-box;
    position: relative;
  }

  @media (max-width: 3200px) {
    .card-wrap {
      width: 10%;
    }
  }

  @media (max-width: 2900px) {
    .card-wrap {
      width: 11.11%;
    }
  }

  @media (max-width: 2600px) {
    .card-wrap {
      width: 12.5%;
    }
  }

  @media (max-width: 2300px) {
    .card-wrap {
      width: 14.29%;
    }
  }

  @media (max-width: 2000px) {
    .card-wrap {
      width: 16.667%;
    }
  }
  @media (max-width: 1700px) {
    .card-wrap {
      width: 20%;
    }
  }
}

.actapp-card {
  width: 100%;
  height: 100%;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.09);
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  // padding-right: 20px;
  box-sizing: border-box;
  position: relative;
  .img-wrapper {
    width: 100%;
    height: 240px;
    text-align: center;
    img {
      object-fit: cover;
      object-position: top center;
      width: 100%;
      height: 100%;
    }
  }

  .card-content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 10px;

    .card-name {
      color: #333;
      font-size: 16px;
      margin-bottom: 8px;
    }

    .card-desc:not(:last-child) {
      margin-bottom: 6px;
      color: #666;
      font-size: 14px;
    }
  }
  .card-overloay{
    width: 100%;
    height: 240px;
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(0,0,0,.45);
    color: #fff;
    font-size: 14px;
    visibility: hidden;
    // z-index: -1;
    opacity: 0;
    transition: opacity .2s ease-in;
  }
  .preview-top{
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .preview-btn{
    width: 130px;
    border-top: dashed 1px rgb(255,255,255);
    border-bottom: dashed 1px rgb(255,255,255);
    border-left: solid 1px rgb(255,255,255);
    border-right: solid 1px rgb(255,255,255);
    height: 36px;
    position: relative;
    border-radius: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #333;
    background-color: #fff;
  }
  .preview-bottom{
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    .btn{
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      cursor: pointer;
      .icon{
        width: 30px;
        height: 30px;
        margin-bottom: 4px;
      }
    }
  }

  &:hover {
    .card-overloay{
      opacity: 1;
      visibility: visible;
    }
  }
}

.el-row {
  overflow: hidden;
}

.actapp-item {
  height: 0;
  padding-bottom: 150%;
  overflow: hidden;

  .actapp-img {
    position: relative;
    overflow: hidden;
    height: 0;
    padding-bottom: 130%;
    cursor: pointer;

    &_container {
      width: 100%;
      height: 100%;

      >img {
        display: block;
        width: 100%;
      }
    }
  }

  .actapp-name {
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 10px 20px;
    text-align: center;
    font-size: 14px;
    color: #000000;
  }
}

.actapp-qrcode {
  position: absolute;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  top: 100%;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba($color: #000000, $alpha: 0.4);
  color: #ffffff;
  transition: top 0.3s ease-out;

  .actapp-container {
    position: relative;
    height: 100%;
    width: 100%;
    text-align: center;
  }

  .qrcode-container {
    background-color: #ffffff;
    padding: 5px;
    border-radius: 4px;
    margin: 40px auto;
    width: 90px;
  }

  .tool-btn {
    background-color: rgba($color: #000000, $alpha: 0.6);
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    padding: 5px 0px;
    cursor: pointer;

    div {
      width: 33%;

      i,
      p {
        width: 100%;
        text-align: center;
      }

      p {
        font-size: 14px;
      }
    }
  }
}

:deep(.el-button--small) {
  padding: 0;
}

.qrcode-container {
  display: flex;
  align-items: center;
  justify-content: center;

  .tips {
    color: #666666;
    margin-left: 20px;
    font-size: 14px;

    div {
      &+div {
        margin-top: 10px;
      }
    }

    a {
      color: var(--el-color-primary);
    }
  }
}</style>
